//! Nacos 日志系统初始化

use tracing_subscriber::{
    fmt::{self, format::FmtSpan},
    layer::SubscriberExt,
    util::SubscriberInitExt,
    EnvFilter,
};

/// 初始化日志系统
///
/// # Panics
///
/// 如果无法构建日志 appender，或者无法设置全局订阅者，则会 panic。
pub fn init_logging(log_dir: Option<&str>, service_name: &str) {
    let env_filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new("info"));

    let formatting_layer = fmt::layer()
        .with_thread_ids(true)
        .with_target(true)
        .with_span_events(FmtSpan::CLOSE)
        .with_writer(std::io::stderr);

    let file_appender_layer = log_dir.map(|dir| {
        let log_file = format!("{}.log", service_name);
        let file_appender = tracing_appender::rolling::daily(dir, log_file);
        fmt::layer()
            .with_ansi(false)
            .json()
            .with_writer(file_appender)
    });

    tracing_subscriber::registry()
        .with(env_filter)
        .with(formatting_layer)
        .with(file_appender_layer)
        .init();
}
